import { ClassificationTreeNode, MediumInstanceInfo } from '@/api/classify/type'
import { reqMediumInstance } from '@/api/classify'

export type TreeNode = {
  id: string
  label: string
  type: number
  children?: TreeNode[]
  disabled?: string
  totalCount: number
  instancedCount: number
}


export const generateTree = async (data: ClassificationTreeNode[]): Promise<TreeNode[]> => {
  const instances: MediumInstanceInfo[] = (await reqMediumInstance()).data

  const parentTree: Map<string, TreeNode> = new Map<string, TreeNode>()
  const subTree: Map<string, TreeNode[]> = new Map<string, TreeNode[]>()
  const instance_map: Map<string, number[]> = new Map<string, number[]>()

  for (const { parentCode, totalCount, instancedCount } of instances) {
    instance_map.set(parentCode, [totalCount, instancedCount])
  }

  for (const node of data) {
    if (node.classificationType === '大类') {
      const parentNode: TreeNode = {
        id: node.classificationCode,
        label: node.classificationName,
        type: 0,
        children: [],
        disabled: 'disabled',
        totalCount: 0,
        instancedCount: 0
      }

      parentTree.set(node.classificationCode, parentNode)
    } else {
      const [totalCount, instancedCount] = instance_map.get(node.classificationCode) || [0, 0]
      const subNode: TreeNode = {
        id: node.classificationCode,
        label: node.classificationName,
        type: 1,
        totalCount,
        instancedCount
      }
      if (subTree.has(node.parentCode)) {
        subTree.get(node.parentCode)?.push(subNode)
      } else {
        subTree.set(node.parentCode, [subNode])
      }
    }
  }

  for (const [key, value] of subTree) {
    const parentNode = parentTree.get(key)
    if (parentNode) {
      parentNode.children = value

      let instanceCount = 0
      for (const node of value) {
        instanceCount += node.instancedCount > 0 ? 1 : 0
      }

      parentNode.instancedCount = instanceCount
      parentNode.totalCount = value.length
    }
  }

  const res = [
    {
      id: '000000',
      label: '基础设施分类码',
      type: 0,
      children: Array.from(parentTree.values()),
      totalCount: 0,
      instancedCount: 0
    }
  ]

  let instanceCount = 0
  for (const node of res[0].children) {
    instanceCount += node.instancedCount > 0 ? 1 : 0
  }

  res[0].instancedCount = instanceCount
  res[0].totalCount = res[0].children.length

  return res
}

